package pl.org.lutra.planner.model.input;

import java.util.Observable;
import java.util.Observer;

import javax.swing.event.EventListenerList;
import javax.swing.text.DocumentFilter;

import pl.org.lutra.planner.log.Log;
import pl.org.lutra.planner.model.ModelEvent;
import pl.org.lutra.planner.model.ModelListener;
import pl.org.lutra.planner.model.ModelObserverEvent;
import pl.org.lutra.planner.model.data.Dive;

public class Input implements Observer {
	boolean changed = false;

	private EventListenerList guiListeners = new EventListenerList();
	private FloatDocumentFilter numberFilter;
	private Dive dive = new Dive();

	public Input() {
		numberFilter = new FloatDocumentFilter();
		numberFilter.addObserver(this);
	}

	public DocumentFilter getDepthDocumentFilter() {
		return numberFilter;
	}

	public DocumentFilter getTimeDocumentFilter() {
		return numberFilter;
	}

	@Override
	public void update(Observable observable, Object argument) {
		if (ModelObserverEvent.INPUT_CHANGED == argument && !changed) {
			Log.debug("Input update " + observable + " : " + argument);

			ModelEvent event = new ModelEvent(observable);
			for (ModelListener listener : getListeners()) {
				listener.inputHasChanged(event);
			}
			changed = true;
		} else if (ModelObserverEvent.CALCULATION_FINISHED == argument) {
			ModelEvent event = new ModelEvent(observable);
			for (ModelListener listener : getListeners()) {
				listener.calculationFinished(event);
			}
			changed = false;
		}
	}

	public void addModelListener(ModelListener listener) {
		guiListeners.add(ModelListener.class, listener);
	}

	private ModelListener[] getListeners() {
		return guiListeners.getListeners(ModelListener.class);
	}

	public Dive getDive() {
		return dive;
	}
}
